package system

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"jgyApi/server/global"
	"jgyApi/server/model/common/response"
	"jgyApi/server/model/system"
	systemReq "jgyApi/server/model/system/request"
	"jgyApi/server/utils"
	"strings"
)

type AppIconApi struct{}

func (i *AppIconApi) Index(c *gin.Context) {
	var ks systemReq.KeySn
	err := c.ShouldBind(&ks)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(ks, utils.KeySnVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	//校验key
	if !utils.IsThrough(ks.Key) {
		response.FailWithMessage("key不对", c)
		return
	}
	var rs utils.CacheResult
	rs = utils.GetRedisCacheField("sn", "value", ks.Sn, "batch")
	if rs.Data == nil || rs.Data == "" {
		response.FailWithMessage("该设备没有设置批次", c)
		return
	}

	type appIcon struct {
		ID      int64  `gorm:"column:id;type:int(10) unsigned;primaryKey;autoIncrement:true" json:"id"`
		Package string `gorm:"column:package;type:text;not null;comment:包名" json:"app_package"`
	}
	var icons []appIcon
	where := fmt.Sprintf("find_in_set(%s, batch)", rs.Data)
	err = global.GVA_DB.Model(&system.AppIcon{}).Where(where).Where("usable=-1").Find(&icons).Error
	if err != nil {
		response.FailWithMessage("没有数据", c)
		return
	}
	var data []string
	for _, v := range icons {
		data = append(data, v.Package)
	}
	res := strings.Join(data, ",")
	response.OkWithDetailed(res, "success", c)
}

func (i *AppIconApi) GetUsableIcon(c *gin.Context) {
	var ks systemReq.KeySn
	err := c.ShouldBind(&ks)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(ks, utils.KeySnVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	//校验key
	if !utils.IsThrough(ks.Key) {
		response.FailWithMessage("key不对", c)
		return
	}
	var rs utils.CacheResult
	rs = utils.GetRedisCacheField("sn", "value", ks.Sn, "batch")
	if rs.Data == nil || rs.Data == "" {
		response.FailWithMessage("该设备没有设置批次", c)
		return
	}

	type appIcon struct {
		ID      int64  `gorm:"column:id;type:int(10) unsigned;primaryKey;autoIncrement:true" json:"id"`
		Package string `gorm:"column:package;type:text;not null;comment:包名" json:"app_package"`
	}
	var icons []appIcon
	where := fmt.Sprintf("find_in_set(%s, batch)", rs.Data)
	err = global.GVA_DB.Model(&system.AppIcon{}).Where(where).Where("usable = 1").Find(&icons).Error
	if err != nil {
		response.FailWithMessage("没有数据", c)
		return
	}
	var data []string
	for _, v := range icons {
		data = append(data, v.Package)
	}
	res := strings.Join(data, ",")
	response.OkWithDetailed(res, "success", c)
}
